from flask import Blueprint,request,jsonify,make_response
from application.models.users.user import *
from util.myredis import r
user_blue = Blueprint('userblue', __name__)
import time
import json
# import redis
import random
from util.captcha.captcha import captcha
#测试
@user_blue.route("/test")
def test():
    id = request.args.get("id")
    return jsonify({"code":200,"id":id})

# 获取图片验证码
@user_blue.route("/getcode")
def getcode():
    #生成图片验证码 text文字， image图片流
    name,text,image = captcha.generate_captcha()
    #从页面获取uuid做为redis key
    uuid = str(request.args.get('uuid'))
    #存入redis
    r.str_add(uuid,str(text),60)
    #以流的方式生成图片验证码
    res = make_response(image)
    res.headers["Content-Type"] = "image/jpg"
    # 存入redis
    # r.set_str(uuid,text)
    return res

@user_blue.route("/sendSmsCode",methods=["POST"])
def sendSmsCode():
    data = request.data
    if data:
        uuid = data["uuid"]
        piccode = data["piccode"]
        mobile = data["mobile"]
        value = r.str_get(uuid)
        if value:
            if piccode.lower() == value.lower():
                mcode = r.str_get(mobile)
                if mcode:
                    return jsonify({"code":10012,"mes":"一分钟内不能重发"})
                scode = random.randint(10000, 99999)
                print(scode)
                flag = sendSmsCode(mobile,scode)
                if flag == True:
                    r.str_add(mobile,scode,60)
                    r.del_str(uuid)
                    return jsonify({"code":200,"mes":"发生成功"})
                else:
                    return jsonify({"code":10013,"mes":"发生验证码失败"})
            else:
                return jsonify({"code":10011,"mes":"图片验证码错误"})
        else:
            return jsonify({"code":10010,"mes":"图片验证码不存在"})


# 发送短信接口
@user_blue.route("/login",methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
        mcode = data["code"]
        mobile = data["mobile"]
        code = r.str_get(mobile)
        if code:
            if int(code)==int(mcode):
                user = UsersModel.query.filter_by(UsersModel.mobile==mobile).first()
                if user:
                    r.del_str(mobile)
                else:
                    u = UsersModel(mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = UsersModel.query.filter_by(UsersModel.mobile==mobile).first()
                # token = myjwt.encode(data={"data":{"uid":user.id,'exp':int(time.time())}})
                token = str(random.randint(100,1000))
                return jsonify({"code":200,"token":token,"userid":user.id})
        else:
            return jsonify({"code":10021,"mes":"验证码错误"})
    else:
        return jsonify({"code":10020,"mes":""})



# @user_blue.route("/reg",methods=["POST","GET"])
# def reg():
#     if request.method == "POST":
#         data = json.loads(request.data)
#         name = data["name"]

# import jwt
# from flask import Blueprint,jsonify,current_app,send_file
# from flask_restful import Api,Resource,reqparse
# from util.myredis import r
# from util.sms_code import send_message
# from application.models.users.user import UsersModel,db
# from captcha.image import ImageCaptcha
# login_bp = Blueprint("login_bp",__name__)
# api = Api(login_bp)
# import random
# import time
# class ImgView(Resource):
#     def get(self):
#         img = ImageCaptcha()
#         code = random.randint(1000,9999)
#         code1 = str(code)
#         img_png = img.generate(code1)
#         return send_file(img_png,mimetype="png")
# api.add_resource(ImgView,"/img")
#
# class SmsView(Resource):
#     def get(self,mobile):
#         code = str(random.randint(1000,9999))
#         send_message(mobile,code)
#         r.str_setex(mobile,60,code)
#         time.sleep(5)
#         return jsonify({"code":200,"msg":"ok"})
# api.add_resource(SmsView,"/sms/<mobile>")
#
# class LoginView(Resource):
#     def post(self):
#         req = reqparse.RequestParser()
#         req.add_argument("nikename")
#         req.add_argument("mobile")
#         args = req.parse_args()
#         if not all([args["nikename"],args["mobile"]]):
#             return jsonify({
#                 "code":400,
#                 "msg":"数据不完整"
#             })
#         user = UsersModel.query.filter(UsersModel.nikename == args["nikename"]).first()
#         if not user:
#             u = UsersModel(nikename=args["nikename"],mobile=args["mobile"])
#             db.session.add(u)
#             db.session.commit()
#             return jsonify({"code":200,"msg":"注册成功"})
#         if user.password != args["password"]:
#             return jsonify({
#                 "code":400,
#                 "msg":"信息错误"
#             })
#         key = current_app.config.get("SECRET_KEY")
#         token = jwt.encode({
#             "user_id":user.id,
#             "exp":int(time.time()) + 30
#         },key,algorithm="HS256")
#         return jsonify({"code":200,"msg":"登录成功","token":token})
# api.add_resource(LoginView,"/login")
#
# 获取图形验证码
# 测试
